let beginBtn = document.querySelector('.begin');
let lis = document.querySelectorAll('.box li:not(.begin)');
let txtBoxUl = document.querySelector('.txtBox ul');
let lastIndex = 0;
let nowIndex = 0;
let pathArr = [0, 1, 2, 4, 7, 6, 5, 3];
let tagetNum = Math.floor(Math.random() * 8 + 80); // [80-87]
let isRun = false;
let speed = 300;
let liHeight = getComputedStyle(txtBoxUl.firstElementChild).height;

beginBtn.addEventListener('click', () => {
  if (!isRun) {
    isRun = true;
    // lis[pathArr[lastIndex]].classList.remove("active");
    nowIndex = 0;
    tagetNum = Math.floor(Math.random() * 8 + 80);
    txtBoxUl.style.transform = `translateY(50px)`;

    run();
  }
});

function run() {
  // debugger;

  // pathArr[nowIndex]  li的下标
  // lis[pathArr[nowIndex]] li的dom节点

  lis[pathArr[lastIndex]].classList.remove('active');
  lis[pathArr[nowIndex % 8]].classList.add('active');

  lastIndex = nowIndex % 8;
  // (nowIndex === pathArr.length) && (nowIndex = 0)

  // 速度的计算(时间间隔)  时间越少 速度越快

  // 慢 -> 快  -> 维持  -> 慢
  if (nowIndex <= 30 && speed > 40) {
    speed -= 25;
  }
  if (nowIndex > 70 && speed < 400) {
    speed += 35;
  }

  // 调整奖品信息轮播
  prize();

  if (nowIndex === tagetNum) {
    isRun = false;
  } else {
    setTimeout(run, speed);
  }
  nowIndex++;
}

/**
 * 奖品信息的轮播
 */
function prize() {
  if (nowIndex) {
    if (speed > 80) {
      txtBoxUl.style.transition = `all 40ms`;
      txtBoxUl.style.transform = `translateY(-${liHeight})`;
    } else {
      txtBoxUl.appendChild(txtBoxUl.firstElementChild);
    }
  } else {
    txtBoxUl.style.transform = `translateY(0px)`;
  }
}

txtBoxUl.addEventListener('transitionend', () => {
  if (nowIndex > 1) {
    txtBoxUl.appendChild(txtBoxUl.firstElementChild);
    txtBoxUl.setAttribute('style', 'transform:translateY(0px)');
  }
});
